<!DOCTYPE html>
<html>
    <head>
        <title>发布订阅模式</title>
    </head>
    <body>
        <script>
            // 事件触发器
            class EventEmitter{
                constructor () {
                    // { 'click': [fn1,fn2],'change':[fn]}
                    this.subs = Object.create(null)
                    // this.subs = {}
                }
                // 注册事件
                $on (eventType,handler) {
                    // 判断this.subs有没有eventType这个属性，如果有把值重新赋给它自己，如果没有赋值空数组
                    this.subs[eventType] = this.subs[eventType] || []
                    this.subs[eventType].push(handler)
                }
                // 触发事件
                $emit (eventType) {
                    if (this.subs[eventType]) {
                        this.subs[eventType].forEach(handler => {
                            handler()
                        });
                    }
                }
            }

            // 测试
            let em = new EventEmitter()
            em.$on('click',()=>{
                console.log('click1')
            })
            em.$on('click',()=>{
                console.log('click1')
            })
            em.$emit('click')
        </script>
    </body>
</html>